/*
 * 官网地站:http://www.mob.com
 * 技术支持QQ: 4006852216
 * 官方微信:ShareSDK   （如果发布新版本的话，我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题，也可以通过微信与我们取得联系，我们将会在24小时内给予回复）
 *
 * Copyright (c) 2013年 mob.com. All rights reserved.
 */

package com.chen.palmar.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.chen.palmar.R;
import com.chen.palmar.common.constant.AppConstant;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.entity.LoginEntity;
import com.chen.palmar.project.init.IdentityActivity;
import com.chen.palmar.project.init.MainActivity;
import com.primb.androidlibs.net.entity.WXEntity;
import com.primb.androidlibs.net.exception.ApiException;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.SendAuth;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.HashMap;

import dmax.dialog.SpotsDialog;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by dell on 2017/5/22.
 * 集成微信sdk的接口
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    public static final String APP_ID = "wxe23828c2955770a1";// 申请的appid
    private IWXAPI api; // IWXAPI 是第三方app和微信通信的openapi接口
    public CompositeSubscription subscription = new CompositeSubscription();
    public SpotsDialog spotsDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entry);
        //注册api
        api = WXAPIFactory.createWXAPI(this, APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);//必须调用此句话
    }

    @Override
    public void onReq(BaseReq baseReq) {
        System.out.println(baseReq);
    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (resp.getType() == 1) {//登陆
                    result = R.string.errcode_success;
                    getOpenId(((SendAuth.Resp) resp).token);
                } else if (resp.getType() == 2) {//分享
                    result = R.string.errcode_share_success;
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if (resp.getType() == 1) {//登陆
                    result = R.string.errcode_cancel;
                } else if (resp.getType() == 2) {//分享
                    result = R.string.errcode_share_cancel;
                }
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                if (resp.getType() == 1) {//登陆
                    result = R.string.errcode_deny;
                } else if (resp.getType() == 2) {//分享
                    result = R.string.errcode_share_deny;
                }
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                if (resp.getType() == 1) {//登陆
                    result = R.string.errcode_unsupported;
                } else if (resp.getType() == 2) {//分享
                    result = R.string.errcode_share_unsupported;
                }
                break;
            default:
                result = R.string.errcode_unknown;
                break;
        }
        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
        this.finish();
    }

    private void getOpenId(String code) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", APP_ID);
        map.put("secret", "896ef000be81e82a4c359f78ee0082b3");
        map.put("code", code);
        map.put("grant_type", "authorization_code");
        Subscription subscribe = DataCenter.wxUserId(AppConstant.OAUTH, map).subscribe(new HttpSubscriber<WXEntity>(this, showLoading("登录中")) {
            @Override
            public void onNext(WXEntity o) {
                if (!TextUtils.isEmpty(o.getOpenid())) {
                    otherLogin(o.getOpenid(), "2");
                } else {
                    Toast.makeText(WXEntryActivity.this, "微信返回ID为空", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                System.out.println(e);
            }
        });
        subscription.add(subscribe);
    }


    private void otherLogin(String userId, String type) {
        HashMap<String, String> map = new HashMap<>();
        map.put("open_id", userId);
        map.put("type", type);
        Subscription subscribe = DataCenter.otherLoginInfo(map).subscribe(new HttpSubscriber<LoginEntity>(this, showLoading("登录中")) {
            @Override
            public void onNext(LoginEntity loginEntity) {
                DataCenter.httpConfig.setUserId(loginEntity.getData().getUserId());
                DataCenter.httpConfig.setLoginToken(loginEntity.getData().getAnycode());
                Intent intent = new Intent();
                if (TextUtils.isEmpty(loginEntity.getData().getType())) {
                    intent.setClass(WXEntryActivity.this, IdentityActivity.class);
                } else {
                    intent.setClass(WXEntryActivity.this, MainActivity.class);
                    intent.putExtra("info", loginEntity.getData());
                }
                startActivity(intent);
            }
        });
        subscription.add(subscribe);
    }

    public SpotsDialog showLoading(String text) {
        if (null == spotsDialog) {
            spotsDialog = new SpotsDialog(this, text);
        }
        spotsDialog.show();
        return spotsDialog;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != subscription) {
            subscription.clear();
            subscription.unsubscribe();
        }
    }
}